package top.my.utils;

import io.vertx.mysqlclient.MySQLException;
import org.apache.log4j.Logger;
import top.my.api.ApiServer;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;

public class DBHelper {
    final static Logger logger = Logger.getLogger(DBHelper.class);
    /**
     * @param tableName 表名
     * @param columns   插入字段
     * @param values    插入值
     * @return
     */
    public static String insert(String tableName, String[] columns, Object[] values) {
        if (columns == null || values == null) {
            throw new MySQLException("columns == null || values == null", -1, "columns,values不能为null");
        }
        if (columns.length != values.length) {
            throw new MySQLException("columns.length != values.length", -1, "columns,values不等");
        }

        StringBuilder sql = new StringBuilder("INSERT INTO ");
        sql.append(tableName).append("(");
        for (int i = 0; i < columns.length; ++i) {
            sql.append(columns[i]).append(" , ");
        }
        sql = new StringBuilder(sql.substring(0, sql.lastIndexOf(" , ")));
        sql.append(") VALUES (");
        for (int i = 0; i < values.length; ++i) {
            String sqlValue;
            if (values[i] instanceof String) {
                sqlValue = "'" + values[i] + "'";
            } else {
                sqlValue = values[i].toString();
            }
            sql.append(sqlValue).append(" , ");
        }
        sql = new StringBuilder(sql.substring(0, sql.lastIndexOf(" , ")));
        sql.append(")");
        logger.info("insert.sql:" + sql.toString());
        return sql.toString();
    }

    /**
     * @param tableName   表名
     * @param columns     修改字段
     * @param values      修改值
     * @param searchKey   查询的字段
     * @param searchValue 查询的值
     * @return
     */
    public static String update(String tableName, String[] columns, Object[] values, String searchKey, String searchValue) {
        if (columns == null || values == null) {
            throw new MySQLException("columns == null || values == null", -1, "columns,values不能为null");
        }
        if (columns.length != values.length) {
            throw new MySQLException("columns.length != values.length", -1, "columns,values不等");
        }
        if (searchKey == null || searchValue ==null) {
            throw new MySQLException("searchKey == null || searchValue ==null", -1, "searchKey,searchValue不能为null");
        }

        StringBuilder sql = new StringBuilder("UPDATE ");
        sql.append(tableName).append(" SET ");
        for (int i = 0; i < columns.length; ++i) {
            if (!columns[i].equals(searchKey)) {
                String sqlValue;
                if (values[i] instanceof String) {
                    sqlValue = "'" + values[i] + "'";
                } else {
                    sqlValue = values[i].toString();
                }
                sql.append(columns[i]).append(" = ").append(sqlValue).append(" , ");
            }
        }
        sql = new StringBuilder(sql.substring(0, sql.lastIndexOf(" , ")));
        String sqlValue;
        if (searchValue instanceof String) {
            sqlValue = "'" + searchValue + "'";
        } else {
            sqlValue = searchValue;
        }
        sql.append(" WHERE ").append(searchKey).append(" = ").append(sqlValue);
        logger.info("update.sql:" + sql.toString());
        return sql.toString();
    }

    /**
     * @param tableName 表名
     * @param columns   多少个删除的字段[uid,uid,uid]
     * @param values    多少个删除的值[8,9,10]
     * @return
     */
    public static String delete(String tableName, String[] columns, Object[] values) {
        if (columns == null || values == null) {
            throw new MySQLException("columns == null || values == null", -1, "columns,values不能为null");
        }
        if (columns.length != values.length) {
            throw new MySQLException("columns.length != values.length", -1, "columns,values不等");
        }

        StringBuilder sql = new StringBuilder("DELETE FROM ");
        sql.append(tableName).append(" WHERE ").append(columns[0]).append(" = ");
        String sqlValue;
        if (values[0] instanceof String) {
            sqlValue = "'" + values[0] + "'";
        } else {
            sqlValue = values[0].toString();
        }
        sql.append(sqlValue);
        for (int i = 1; i < columns.length; ++i) {
            if (values[i] instanceof String) {
                sqlValue = "'" + values[i] + "'";
            } else {
                sqlValue = values[i].toString();
            }
            sql.append(" OR ").append(columns[i]).append(" = ").append(sqlValue);
        }
        logger.info("delete.sql:" + sql.toString());
        return sql.toString();
    }

    /**
     * @param tableName 删除整个表的表名
     * @return
     */
    public static String deleteTable(String tableName) {
        StringBuilder sql = new StringBuilder("DELETE FROM ");
        sql.append(tableName);
        logger.info("deleteTable.sql:" + sql.toString());
        return sql.toString();
    }

    /**
     * @param tableName 表名
     * @param column    查询字段
     * @param value     查询的值
     * @return
     */
    public static String query(String tableName, String column, Object value) {
        String sqlValue;
        if (value instanceof String) {
            sqlValue = "'" + value + "'";
        } else {
            sqlValue = value.toString();
        }
        String sql = "SELECT * FROM " + tableName + " WHERE " + column + " = " + sqlValue;
        logger.info("query.sql:" + sql.toString());
        return sql;
    }

    /**
     * @param tableName  表名
     * @param columns    查询字段
     * @param operations 运算符
     * @param values     查询的值
     * @return
     */
    public static String query(String tableName, String[] columns, String[] operations, Object[] values) {
        if (columns == null || operations == null || values == null) {
            throw new MySQLException("columns == null || operations == null || values == null", -1, "columns,operations,values不能为null");
        }
        if (columns.length != values.length || columns.length != operations.length) {
            throw new MySQLException("columns.length != values.length || columns.length != operations.length", -1, "columns,operations,values不等");
        }
        StringBuilder sql = new StringBuilder("SELECT * FROM ");
        sql.append(tableName).append(" WHERE ").append(columns[0]).append(operations[0]);
        String sqlValue;
        if (values[0] instanceof String) {
            sqlValue = "'" + values[0] + "'";
        } else {
            sqlValue = values[0].toString();
        }
        sql.append(sqlValue);

        for (int i = 1; i < columns.length; ++i) {
            if (values[i] instanceof String) {
                sqlValue = "'" + values[i] + "'";
            } else {
                sqlValue = values[i].toString();
            }
            sql.append(" AND ").append(columns[i]).append(operations[i]).append(sqlValue);
        }
        //logger.debug("query.sql:" + sql);
        return sql.toString();
    }


    /**
     * @param value  根据那个字段
     * @param isDesc true:降序 false:升序
     * @return
     */
    public static String orderBy(String value, boolean isDesc) {
        String rule = isDesc ? " DESC" : " ASC";
        String sql = " ORDER BY " + value + rule;
        logger.info("orderBy.sql:" + sql.toString());
        return sql;
    }

    public static boolean reflectObject(List<String> columnList, List<String> valueList, Object obj) {
        try {
            Class<?> clazz = obj.getClass();
            Field[] fields = clazz.getDeclaredFields();
            int length = fields.length;
            //logger.debug("fields.length :" + length);
            for (Field field : fields) {
                field.setAccessible(true);
                Object value = field.get(obj);
                if (value == null) {
                    continue;
                }
                columnList.add(field.getName());
                valueList.add(value.toString());
                //logger.debug(field.getName() + "-->" + value);
            }
            return true;
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return false;
    }

    public static HashMap<String, Class> classMap = new HashMap<>();

    //获取泛型的类
    public static <T> Class<T> getGenericsClass(Object obj) {
        //logger.debug("params: " + obj.getClass().getName());
        Type genType = obj.getClass().getGenericInterfaces()[0];
        //logger.debug("genType: " + genType.getTypeName());
        /*Class<T> clazz = classMap.get(genType.getTypeName());
        if (clazz != null) {
            return clazz;
        }*/
        if (genType instanceof ParameterizedType) {
            Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
            Class<T> clazz = (Class<T>) params[0];
            //logger.debug("params: " + claz.getName());
            //classMap.put(genType.getTypeName(), clazz);
            return clazz;
        }
        return null;
    }
}
